<template>
  <div style="padding:30px;">
    <el-form ref="queryFrom" :inline="true" :model="queryFrom" class="demo-form-inline">
      <el-form-item prop="code">
        <el-input v-model="queryFrom.name" class="el-input--mini" placeholder="品牌名称" prefix-icon="el-icon-search" maxlength="10" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-button--mini" icon="el-icon-search" @click="queryShopBrand">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-button--mini" icon="el-icon-delete" @click="onReset('queryFrom')">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-button--mini" icon="el-icon-plus" @click="onAddKeyword">添加</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      lazy
      element-loading-text="拼命加载中"
      :row-style="{height:'10px'}"
      :cell-style="{padding:'0px'}"
    >
      <el-table-column
        prop="id"
        label="ID"
        sortable
        width="100"
      />
      <el-table-column
        prop="name"
        label="品牌商名称"
        width="130"
        align="center"
      />
      <el-table-column
        prop="desc"
        label="品牌商介绍"
        width="480"
        align="center"
      />
      <el-table-column prop="picUrl" align="center" label="品牌商图片" width="150px">
        <template slot-scope="scope">
          <el-image :src="scope.row.picUrl">
            <div slot="placeholder" class="image-slot">
              加载中<span class="dot">...</span>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="floorPrice"
        label="底价（单位：元）"
        width="180"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.floorPrice | floorPricefilters }}
        </template>
      </el-table-column>
      <el-table-column prop="deleted" align="center" label="状态" width="150px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.deleted | tagTypeFilter">
            {{ scope.row.deleted | statusfilters }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="操作" align="center">
        <template slot-scope="scope">
          <div>
            <el-button type="primary" class="el-button--mini" size="small" icon="el-icon-edit" @click="onEditKeyword(scope.row)">编辑</el-button>
            <el-button type="danger" class="el-button--mini" size="small" icon="el-icon-close" @click="onDeleted(scope.row)">{{ scope.row.deleted ===0? '删除':'恢复使用' }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        :total="page.totalCount"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="restForm">
      <el-form ref="from" :model="from" :rules="rules">
        <el-form-item label="品牌商名称" :label-width="formLabelWidth" prop="name">
          <el-input
            v-model="from.name"
            autocomplete="off"
            prefix-icon="el-icon-edit"
            maxlength="10"
            show-word-limit
            class="el-input--mini"
          />
        </el-form-item>
        <el-form-item label="主营类目" :label-width="formLabelWidth" prop="defaultCategoryId">

          <el-cascader
            ref="cascaderHandle"
            :key="refresh"
            v-model="value"
            :options="categoryList"
            :props="{ expandTrigger: 'hover' }"
            clearable
            :multiple="false"
            class="el-input--medium"
            @change="handleChange"
          />

        </el-form-item>
        <el-form-item label="介绍" :label-width="formLabelWidth" prop="desc">
          <el-input
            v-model="from.desc"
            type="textarea"
            autosize
            autocomplete="off"
            prefix-icon="el-icon-search"
            maxlength="200"
            show-word-limit
            class="el-input--mini"
          />
        </el-form-item>
        <el-form-item label="品牌商图片" :label-width="formLabelWidth" prop="picUrl">

          <el-upload
            class="avatar-uploader"
            :action="doUpload"
            :headers="{ token: token }"
            :show-file-list="false"
            :auto-upload="true"
            list-type="picture-card"
            accept="image/jpeg,image/gif,image/png,image/bmp"
            :on-success="onSuccessImgUrl"
          >
            <label class="el-upload-list__item-status-label">
              <i class="el-icon-upload-success el-icon-check" />
            </label>
            <img v-if="from.picUrl" :src="from.picUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>

        </el-form-item>

        <el-form-item label="底价" :label-width="formLabelWidth" prop="floorPrice">
          <el-input
            v-model="from.floorPrice"
            autocomplete="off"
            prefix-icon="el-icon-edit"
            maxlength="12"
            show-word-limit
            class="el-input--mini"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="提货时间设置" :label-width="formLabelWidth" prop="fetchTimeRules">
          <el-time-picker
            v-model="from.fetchTimeRules"
            value-format="HH:mm:ss"
            format="HH:mm:ss"
            is-range
            arrow-control
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
            class="el-input--mini"
            @change="getTimePickerValue"
          />
        </el-form-item>
        <el-form-item label="自提地址" :label-width="formLabelWidth" prop="address">
          <el-input
            v-model="from.address"
            autocomplete="off"
            prefix-icon="el-icon-edit"
            maxlength="100"
            show-word-limit
            class="el-input--mini"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="el-button--mini" @click="cancelChange('from');dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" class="el-button--mini" @click="onSubmitShopBrand('from');">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { queryShopBrand, updateShopBrand, addShopBrand } from '@/api/goods/index'
import { queryShopCategoryList } from '@/api/shop/shopcategory'
import { mapGetters } from 'vuex'
export default {
  filters: {

    tagTypeFilter(status) {
      return status === 1 ? 'danger' : 'gray'
    },
    floorPricefilters(value) {
      return value / 100
    },
    isDefaultfilters(val) {
      if (val == null || val === '') {
        return '--'
      } else {
        if (val === 0) {
          return '否'
        }
        if (val === 1) {
          return '是'
        }
      }
    },
    timefilters(val) {
      if (val == null || val === '') {
        return '暂无时间'
      } else {
        const d = new Date(val) // val 为表格内取到的后台时间
        const month =
          d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
        const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
        const hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours()
        const min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()
        const sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds()
        const times = d.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + sec
        return times
      }
    },
    statusfilters(val) {
      if (val == null || val === '') {
        return '--'
      } else {
        if (val === 0) {
          return '已生效'
        }
        if (val === 1) {
          return '已删除'
        }
      }
    }

  },

  data() {
    return {
      doUpload: process.env.VUE_APP_BASE_API + '/qiniuConfig/upload',

      options: [{
        value: 0,
        label: '正常'
      }, {
        value: 1,
        label: '禁用'
      }],
      isDefaultOptions: [{
        value: 0,
        label: '否'
      }, {
        value: 1,
        label: '是'
      }],
      queryFrom: {
        name: ''
      },
      from: {
        id: '',
        name: '',
        desc: '',
        picUrl: '',
        floorPrice: '',
        defaultCategoryId: '',
        address: '',
        fetchTimeRules: ''

      },
      page: {
        'rowCount': 10,
        'currentPage': 1,
        'pageSize': 10,
        'pageCount': 2,
        'totalCount': 0,
        'orderBy': null,
        'outofBounds': false,
        'limitStart': 0
      },
      tableData: [],
      value: [],
      refresh: 0,
      dialogFormVisible: false,
      title: '',
      isAdd: false,
      formLabelWidth: '130px',
      categoryList: [],
      rules: {
        name: [{ required: true, message: '请填写品牌商名称', trigger: 'blur' }],
        //  defaultCategoryId: [{ type: 'array', required: true, message: '请选择品牌商类目', trigger: 'change' }],
        desc: [{ required: true, message: '请填写品牌商介绍', trigger: 'change ' }],
        picUrl: [{ required: true, message: '请上传品牌商图片', trigger: 'change ' }],
        floorPrice: [{ required: true, message: '请填写底价', trigger: 'blur' }],
        address: [{ required: true, message: '请填写自提地址', trigger: 'blur' }],
        fetchTimeRules: [{ required: true, message: '请填写提货时间', trigger: 'blur' }]
      },
      loading: true
    }
  },
  computed: {
    ...mapGetters(['fileUpload', 'token'])
  },
  created() {
    this.queryShopBrand()
  },
  methods: {

    queryShopBrand() {
      this.loading = true
      const queryPage = { page: this.page }
      var qq = Object.assign(queryPage, this.queryFrom)
      queryShopBrand(qq).then(response => {
        this.loading = false
        this.tableData = response.data.list
        this.page = response.data.page
      })
    },
    onAddKeyword() {
      this.dialogFormVisible = true
      this.title = '新增'
      this.isAdd = true
      this.clearForm()
      this.categoryList = []
      this.value = []
      queryShopCategoryList({ name: '' }).then(response => {
        // this.categoryList = response.data
        const data = response.data
        data.forEach(element => {
          if (element.children != null && element.children.length > 0) {
            const children = []
            element.children.forEach(chi => {
              children.push({
                label: chi.name,
                value: chi.id
              })
            })
            this.refresh = this.refresh + 1
            this.categoryList.push({
              label: element.name,
              value: element.id,
              children: children
            })
          }
        })
      })
    },
    onEditKeyword(row) {
      this.dialogFormVisible = true
      this.title = '编辑'
      this.isAdd = false

      this.from.id = row.id
      this.from.name = row.name
      this.from.desc = row.desc
      this.from.picUrl = row.picUrl
      this.from.floorPrice = row.floorPrice / 100
      this.from.defaultCategoryId = row.defaultCategoryId
      this.from.address = row.address
      if (row.fetchTimeRules !== null) {
        this.from.fetchTimeRules = row.fetchTimeRules.split('-')
      } else {
        this.from.fetchTimeRules = []
      }

      this.categoryList = []
      this.value = []
      queryShopCategoryList({ name: '' }).then(response => {
        // this.categoryList = response.data
        const data = response.data
        data.forEach(element => {
          if (element.children != null && element.children.length > 0) {
            const children = []
            element.children.forEach(chi => {
              if (chi.id === row.defaultCategoryId) {
                this.value.push(element.id, chi.id)
              }
              children.push({
                label: chi.name,
                value: chi.id
              })
            })
            this.refresh = this.refresh + 1
            this.categoryList.push({
              label: element.name,
              value: element.id,
              children: children
            })
          }
        })
      })
      // this.$refs[`cascaderHandle`][0].value = row.defaultCategoryId
    },
    onSubmitShopBrand(formName) {
      this.$refs[formName].validate((valida) => {
        if (valida) {
          if (!this.isAdd) {
            this.from.deleted = null
            if (this.from.fetchTimeRules !== null) {
              this.from.fetchTimeRules = this.from.fetchTimeRules[0] + ' - ' + this.from.fetchTimeRules[1]
            }
            const obj = this.$refs['cascaderHandle'].getCheckedNodes()
            this.from.defaultCategoryId = obj[0].data.value
            updateShopBrand(this.from).then(response => {
              this.$notify({ title: response.msg, duration: 1000, type: 'success' })
              this.dialogFormVisible = false
              this.clearForm()
              this.queryShopBrand()
            })
          } else {
            this.from.deleted = false
            if (this.from.fetchTimeRules !== null) {
              this.from.fetchTimeRules = this.from.fetchTimeRules[0] + ' - ' + this.from.fetchTimeRules[1]
            }
            const obj = this.$refs['cascaderHandle'].getCheckedNodes()
            this.from.defaultCategoryId = obj[0].data.value
            addShopBrand(this.from).then(response => {
              this.$notify({ title: response.msg, duration: 1000, type: 'success' })
              this.dialogFormVisible = false
              this.queryShopBrand()
              this.clearForm()
            })
          }
        } else {
          return false
        }
        this.$refs[formName].clearValidate()
      })
    },
    onDeleted(row) {
      const title = row.deleted === 0 ? '删除' : '恢复'
      this.$confirm('确认要' + title + '该品牌商: ' + row.name + ' 吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.clearForm()
        this.from.id = row.id
        this.from.deleted = row.deleted === 0 ? 1 : 0

        updateShopBrand(this.from).then(response => {
          this.$notify({ title: response.msg, duration: 1000, type: 'success' })
          this.clearForm()
          this.queryShopBrand()
        })
      }).catch(() => {
      })
    },
    onReset(formName) {
      this.$refs[formName].resetFields()
      this.queryFrom.name = null
    }, handleSizeChange(val) {
      this.page.pageSize = val
      this.queryShopBrand()
    },
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.queryShopBrand()
    },
    cancelChange(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].clearValidate()
      this.clearForm()
    },
    clearForm() {
      this.from.id = null
      this.from.name = null
      this.from.desc = null
      this.from.picUrl = null
      this.from.floorPrice = null
      this.from.defaultCategoryId = null
      this.from.address = null
      this.from.fetchTimeRules = null
      this.value = null
    },
    handleChange(value) {
      // this.$refs.cascaderHandle.dropDownVisible = false
      const obj = this.$refs['cascaderHandle'].getCheckedNodes()
      console.log(obj[0].data.value) // 打印出当前选择的value所对应的对象
    },
    restForm() {
      this.$refs.from.resetFields()
    },
    getTimePickerValue(value) {
      console.log(value)
    },
    onSuccessImgUrl(file) {
      this.$message.success(file.msg)
      this.from.picUrl = file.data
    }
  }
}

</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }
</style>
